Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 26/30 Β· 107.0 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Some implementations allow the prototype to be accessed or set
explicitly using the __proto__ slot as shown below.

function Base() {
this.anOverride = function() { console.log("Base::anOverride()"); };
this.aBaseFunction = function() { console.log("Base::aBaseFunction()");
};
}
function Derived() {
this.anOverride = function() { console.log("Derived::anOverride()"); };
}
const base = new Base();
Derived.prototype = base; // Must be before new Derived()
Derived.prototype.constructor = Derived; // Required to make
`instanceof` work
const d = new Derived(); // Copies Derived.prototype to d instance's
hidden prototype slot.
d instanceof Derived; // true
d instanceof Base; // true
base.aBaseFunction = function() {
console.log("Base::aNEWBaseFunction()"); };
d.anOverride(); // Derived::anOverride()
d.aBaseFunction(); // Base::aNEWBaseFunction()
console.log(d.aBaseFunction == Derived.prototype.aBaseFunction); // true
console.log(d.__proto__ == base); // true in Mozilla-based
implementations and false in many others.

The following shows clearly how references to prototypes are copied on
instance creation, but that changes to a prototype can affect all
instances that refer to it.

function m1() { return "One"; }
function m2() { return "Two"; }
function m3() { return "Three"; }
function Base() {}
Base.prototype.m = m2;
const bar = new Base();
console.log("bar.m " + bar.m()); // bar.m Two
function Top() { this.m = m3; }
const t = new Top();
const foo = new Base();
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
console.log("foo.m " + foo.m()); // foo.m Two
const baz = new Base();
console.log("baz.m " + baz.m()); // baz.m Three
t.m = m1; // Does affect baz, and any other derived classes.
console.log("baz.m1 " + baz.m()); // baz.m1 One

In practice many variations of these themes are used, and it can be both
powerful and confusing.


──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────